#!/usr/bin/env python
# -*- coding: utf-8 -*-
#  insert_content.py
#  description

#  Created by zhouzongli633 on 2020/6/3 10:10 上午.
#  Copyright ©Intellectus All rights reserved.

import os
import sys
import django
import base64
from django.db.models import Max
from pydocx import PyDocX
from bs4 import BeautifulSoup
import bs4
import time
from NICU2HOME import settings
from django.utils import timezone
from Common.Storage_Blob_Manager import StorageManage
from Common.logger import app_log
from Common.utils import CommonUtil

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'NICU2HOME.settings_loc')
django.setup()
from EducationContent.models import EducationFeeds, EducationCategory, Hospital

# NCH
# hospital = 3
# source_default = 3

# PWH
# hospital = 4
# source_default = 4

# RUSH
hospital = 5
source_default = 5


# CDH
# hospital = 1
# source_default = 2


def upload_image_to_storage(image_data, content_type):
    try:

        year_month = CommonUtil.get_now_time_string('%Y_%m')
        time_stamp = CommonUtil.get_now_time_timestamp()
        name = "image{}.{}".format(time_stamp, content_type.split('/')[1])
        file_name = "{}/{}".format(year_month, name)

        manager = StorageManage()
        manager.upload_file(image_data, file_name, content_type=content_type)
        image_path = "{}/{}/{}".format(settings.STORAGE_ACCOUNT_URL, settings.STORAGE_CONTAINER_NAME, file_name)
        return image_path
    except Exception as e:
        raise e


def get_file_dict(path):
    try:
        html = PyDocX.to_html(path)
        soup = BeautifulSoup(html, features="html.parser")
        all_p = soup.find_all(["p", "ul"])
        image_url, title, bullets1, bullets2, source, img, title_video, title_image, title_type = "", "", "", "", "", "", "", "", "image"
        body_info = ""
        for it in all_p:
            if it.text.startswith('Title: '):
                title = it.text[7:]
                continue

            if it.text.startswith('Bullets: ') and len(it.text) > 10:
                bullets1 = it.text[9:]
                continue

            if it.name == "ul":
                if len(it.contents) > 0:
                    bullets1 = it.contents[0].text
                if len(it.contents) > 1:
                    bullets2 = it.contents[1].text
                continue

            if it.text.startswith('Source: '):
                source = it.text[8:]
                continue
            if it.text.startswith('https://pixabay.com/photos/'):
                source = it.text[8:]
                continue

            if type(it.contents[0]) is bs4.element.Tag:
                if it.contents[0].name == "img":
                    img_tag = it.contents[0]
                    base64_str = img_tag['src'].split(';base64,')[1]
                    content_type = img_tag['src'].split(';base64,')[0].split(':')[1]
                    binary_img_data = base64.b64decode(base64_str)
                    image_url = upload_image_to_storage(binary_img_data, content_type=content_type)
                    continue
                if len(it.contents[0].contents) > 0 and type(it.contents[0].contents[0]) is bs4.element.Tag:
                    if it.contents[0].contents[0].name == "img":
                        img_tag = it.contents[0].contents[0]
                        base64_str = img_tag['src'].split(';base64,')[1]
                        content_type = img_tag['src'].split(';base64,')[0].split(':')[1]
                        binary_img_data = base64.b64decode(base64_str)
                        image_url = upload_image_to_storage(binary_img_data, content_type=content_type)
                        continue

            if it.text.startswith('Related Content'):
                break

            body_info += str(it)

        ret = {
            "title": title,
            "bullets1": bullets1,
            "bullets2": bullets2,
            "source": source,
            "img": img,
            "title_type": title_type,
            "title_image": image_url,
            "title_video": None,
            "body_info": body_info,
        }

        return ret
    except Exception as e:
        raise e


def insert_content(file_path, hospital_id, category_id):
    try:
        post_param = get_file_dict(file_path)
        date = timezone.now()
        current_max_order = EducationFeeds.objects.filter(
            hospital_id=hospital_id,
            category_id=category_id
        ).all().aggregate(Max('content_order'))['content_order__max']
        content_order = current_max_order + 1 if current_max_order else 1

        record = EducationFeeds(
            hospital_id=hospital_id,
            category_id=category_id,
            title=post_param['title'],
            title_SP=post_param['title'] + '[SP]',
            summary_1=post_param['bullets1'] if 'bullets1' in post_param else None,
            summary_2=post_param['bullets2'] if 'bullets2' in post_param else None,
            summary_1_SP=post_param['bullets1'] + '[SP]' if 'bullets1' in post_param else '[SP]',
            summary_2_SP=post_param['bullets2'] + '[SP]' if 'bullets2' in post_param else '[SP]',
            source=1 if post_param['source'] == 'N2H' else source_default,
            tags='',
            title_media_type=post_param['title_type'],
            title_media_url=post_param['title_image'],
            title_media_url_SP=post_param['title_image'],
            page_info=post_param['body_info'],
            page_info_SP=post_param['body_info'] + '[SP]',
            content_order=content_order,
            related_content_1=None,
            related_content_2=None,
            related_content_3=None,
            related_content_4=None,
            time_of_delivery_week=0,
            time_of_delivery_day=0,
            time_of_delivery_hour=0,
            created_at=date,
            updated_at=date
        )
        app_log.info("title:{}".format(record.title))
        app_log.info("source:{}".format(record.source))
        app_log.info("title_media_url:{}".format(record.title_media_url))
        record.save()
        return hospital_id, category_id, file_path

    except Exception as e:
        app_log.exception(str(e))


def insert_contents():
    try:
        hospital_id = hospital
        path = "/Users/zhouzongli/Desktop/TOTAL EDUCATION CONTENT/Rush - ALL EDUCATION CENTER CONTENT"

        def getFiles(path, suffix):
            res = []
            for root, directory, files in os.walk(path):
                for filename in files:
                    name, suf = os.path.splitext(filename)
                    if suf == suffix:
                        res.append(os.path.join(root, filename))
            return res

        index = 0
        success = 0
        failure = 0
        all_files = getFiles(path, '.docx')
        for file in all_files:
            index += 1
            file_path = file
            app_log.info(file_path)
            category = str(file.rsplit("/", 2)[-2])
            data = EducationCategory.objects.filter(title=category, hospital_id=hospital_id).values("cid").first()
            if data:
                insert_content(file_path, hospital_id, data['cid'])
                success += 1
            else:
                app_log.info("============insert ERROR:{}".format(file_path))
                failure += 1
            app_log.info('progress:{}/{},success:{}, failure:{}'.format(index, len(all_files), success, failure))
        app_log.info("hospital[{}] [{}] upload finish".format(hospital_id, category))
    except Exception as e:
        app_log.exception(str(e))


def check_conents():
    pass


if __name__ == "__main__":
    # insert_contents()
    # check_conents()
    from Baby import models
    from django.db.models import F, Q, When
    # email = "test33@mail.com"
    # spouse_id = models.Users.objects.filter(email=email).values("spouse_id").first()
    # print(spouse_id["spouse_id"])
    # baby_id = 23
    # data = models.UsersBabies.objects.filter(babies_id=baby_id).values("family_id").first()
    # family_id = data["family_id"]
    # family_parent_data = models.UsersBabies.objects.filter(family_id=family_id).values("users_id").all().distinct()
    # print(family_parent_data)
    # for i in family_parent_data:
    #     print(i)
    # group = "groupA"
    # baby_query = models.Babies.objects.filter(group=group).all()
    # print(baby_query)
    # data = models.Medications.objects.filter(When(name=models.Medications.name, then="name"))
    data = models.Babies.objects.filter(users_babies__family_id=1).all()
    print(data)